package com.qf.cx.simplenms.subscriber.impl;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.qf.cx.simplenms.subscriber.api.HttpChannel;
import com.qf.cx.simplenms.subscriber.type.exception.InvalidURIException;

public class HttpChannelImpl implements HttpChannel {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	private final URL url;
	private final HttpPost post;
	private final CloseableHttpClient httpClient = HttpClients.createDefault();

	public HttpChannelImpl(String notificationURI) throws InvalidURIException {
		try {
			url = new URL(notificationURI);
			post = new HttpPost();
			initPost();
		} catch (MalformedURLException | URISyntaxException e) {
			logger.error("malformed URL: ", e);
			throw new InvalidURIException("malformed URL: ", e);
		}
	}

	private void initPost() throws URISyntaxException {
		post.setURI(url.toURI());
		post.setHeader("content-type", "application/json; charset=UTF-8");
		post.setHeader("Accept", "text/xml");
		post.setHeader("Cache-control", "no-cache");
		post.setHeader("Connection", "keep-alive");
		post.setHeader("Pragma", "no-cache");
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(1000)
				.setSocketTimeout(5000).build();
		post.setConfig(requestConfig);
	}

	@Override
	public int post(String content) throws IOException {
		byte[] bytes = content.getBytes("UTF-8");
		HttpEntity requestEntity = new ByteArrayEntity(bytes);
		post.reset();
		post.setEntity(requestEntity);
		CloseableHttpResponse rc = httpClient.execute(post);
		return rc.getStatusLine().getStatusCode();
	}

	@Override
	public void close() {
		try {
			httpClient.close();
		} catch (IOException ignore) {
			logger.error("close http client failed");
		}
	}

}
